#include "packing.h"
#include <algorithm>


Packing::Packing(int id, int maxW, int maxH)
 :	id(id),
 maxWidth(maxW), maxHeight(maxH), height(0), width(0)
{
	//ctor
}

Packing::~Packing()
{
	//dtor
}

int Packing::name() const
{
	return id;
}

void Packing::replace(Packing b)
{
	Rectangle r(-b.name());
	Tiles::iterator
	result = find_if(tiles.begin(),
						tiles.end(),
						std::bind2nd(Rectangle::SameId(),r));



	b.offset(result->left(), result->bottom());

	const Tiles &list = b.getTiles();
	tiles.insert(result,list.begin(), list.end());
	tiles.erase(result);

}

void Packing::insert(const Rectangle& x, int beforeID)
{
	if(beforeID == 0)
	{
		tiles.push_front(x);
	}
	else
	{
		Rectangle r(beforeID);
		Tiles::iterator
		result = find_if(tiles.begin(),
							tiles.end(),
							std::bind2nd(Rectangle::SameId(),r));
		tiles.insert(result, x);
	}
	if(x.top() > height) height = x.top();
	if(x.right() > width) width = x.right();
}

void Packing::offset(int x, int y)
{
	for(Tiles::iterator i = tiles.begin(); i != tiles.end(); i++)
	{
		i->place(i->left()+x, i->bottom()+y);
	}
	height += y;
	width += y;

}

const std::list<Rectangle>& Packing::getTiles() const
{
	return tiles;
}

Rectangle Packing::getBounds() const
{
	Rectangle r(-id, height, width);
	return r;
}

Rectangle Packing::getMaxBounds() const
{
	Rectangle r(-id, maxHeight, maxWidth);
	return r;
}



